package com.founder.android.db;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CityStoreService extends BaseStoreService {
	
	public CityStoreService(SQLiteDatabase db) {
		super(db);
	}
	
	/**
	* 根据ID查找
	* @param id 要查的ID
	* @return 对应的对象, 如果未找到返回null
	*/
	public City find(Integer id) {
		City city = null;
		Cursor cursor = db.rawQuery("SELECT * FROM city WHERE id=?", 
				new String[] { id.toString() });
		try {
			if (cursor.moveToNext()) {
				city = initCity(cursor);
			}
		} finally {
			cursor.close();
		}
		return city;
	}
	
	/**
	* 根据名字查找
	* @param id 要查的名字
	* @return 对应的对象, 如果未找到返回null
	*/
	public City findByName(String name) {
		City city = null;
		Cursor cursor = db.rawQuery("SELECT * FROM city WHERE name=?", 
				new String[] { name });
		try {
			if (cursor.moveToNext()) {
				city = initCity(cursor);
			}
		} finally {
			cursor.close();
		}
		return city;
	}
	
	/**
	* 查询所有对象
	* @return 对象集合, 如未找到, 返回一个size()为0的List
	*/
	public List<City> findAll() {
		List<City> citys = new ArrayList<City>();
		Cursor cursor = db.rawQuery("SELECT * FROM city ORDER BY id", null);
		try {
			while (cursor.moveToNext()) {
				citys.add(initCity(cursor));
			}
		} finally {
			cursor.close();
		}
		return citys;
	} 
	
	/**
	 * 保存对象
	 * @param user
	 */
	public void save(City city) {
		int cityId = city.getId();
		City dbCity = find(cityId);
		if (dbCity == null) {
			db.execSQL("INSERT INTO city(name, file_name) VALUES(?,?)", 
					new Object[] {city.getName(), city.getFileName()});
		} else {
			db.execSQL("UPDATE city SET name=?, file_name=? WHERE id=?", 
					new Object[] {city.getName(), city.getFileName(), city.getId() });
		}
	}
	
	/**
	* 根据ID删除
	* @param id 要删除的ID
	*/
	public void remove(Integer id) {
		db.execSQL("DELETE FROM city WHERE id=?", new Object[] { id });
	}
	
	private City initCity(Cursor cursor) {
		Integer id = cursor.getInt(cursor.getColumnIndex("id"));
		String name = cursor.getString(cursor.getColumnIndex("name"));
		String fileName = cursor.getString(cursor.getColumnIndex("file_name"));
		return new City(id, name, fileName);
	}
}
